package com.datoucai.common;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import com.alibaba.csp.sentinel.context.Context;
import com.alibaba.csp.sentinel.context.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class SentinelRequestOriginParser implements RequestOriginParser {
    @Override
    public String parseOrigin(HttpServletRequest httpServletRequest) {
        Context context = ContextUtil.getContext();
        if(context == null) {
            return null;
        }
        String origin = httpServletRequest.getParameter("origin");
        if(StringUtils.isBlank(origin)) {
            origin = httpServletRequest.getHeader("origin");
        }
        log.info("ip:{},授权规则的信息:{}",httpServletRequest.getRemoteAddr(),origin);
        context.setOrigin(origin);
        if(StringUtils.isBlank(origin)) {
            return httpServletRequest.getRemoteAddr();
        }
        return origin;
    }
}
